﻿using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
using System.Text;

namespace spark
{
    public class Util
    {

        private static string host = "http://spark.ycst.work:8888";
        /**
         * 搜索项目
         */
        public static JObject SearchProjects()
        {
            return request(host + @"/project/search");
        }

        /**
         * 获取项目全部组件
         */
        public static JObject getAllComponents(string projectId)
        {
            return request(host + "/component/getAll?project_id=" + projectId);
        }

        /**
         * 下载文件
         */
        public static bool Download(string projectId, string etag, string filename)
        {
            var url = host + @"/component/download?project_id=" + projectId + "&etag=" + etag;
            using (var web = new WebClient())
            {
                try
                {
                    web.DownloadFile(url, filename);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        /**
         * 请求
         */
        private static JObject request(string url)
        {
            var request = HttpWebRequest.Create(url);
            request.Method= "GET";
            var response = request.GetResponse();
            if (response.ContentType == "application/json")
            {
                var res = response.GetResponseStream();
                var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                return JObject.Parse(reader.ReadToEnd());
            }
            return null;
        }
    }
}
